﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;

public class CSVUtil
{

    private static Dictionary<string, Dictionary<string, string>> LoadCsvFile(string filePath)
    {
        var result = new Dictionary<string, Dictionary<string, string>>();
        filePath = filePath.Replace("\\", "/");
        string[] fileData = File.ReadAllLines(filePath);

        // CSV文件的第一行为Key字段，第二行开始是数据。第一个字段一定是ID
        string[] keys = fileData[1].Split(',');

        for (int i = 3; i < fileData.Length; i++)
        {
            string[] line = fileData[i].Split(',');

            // 以ID为key值，创建一个新的集合，用于保存当前行的数据
            string id = line[0];
            result[id] = new Dictionary<string, string>();

            for (int j = 0; j < line.Length; j++)
            {
                // 每一行的数据存储规则：Key字段-Value值
                result[id][keys[j]] = line[j];
            }
        }

        return result;
    }

    /// <summary>
    /// 加载CSV结构数据
    /// </summary>
    /// <typeparam name="T_CsvData"></typeparam>
    /// <param name="csvFilePath"></param>
    /// <returns></returns>
    public static Dictionary<int, T_CsvData> LoadCsvData<T_CsvData>(string csvFilePath)
    {
        var dict = new Dictionary<int, T_CsvData>();
        Dictionary<string, Dictionary<string, string>> result = LoadCsvFile(csvFilePath);

        // 遍历每一行数据
        foreach (string id in result.Keys)
        {
            // CSV的一行数据
            Dictionary<string, string> datas = result[id];

            // 读取Csv数据对象的属性
            PropertyInfo[] props = typeof(T_CsvData).GetProperties();

            // 使用反射，将CSV文件的数据赋值给CSV数据对象的相应字段，要求CSV文件的字段名和CSV数据对象的字段名完全相同
            T_CsvData obj = System.Activator.CreateInstance<T_CsvData>();

            foreach (PropertyInfo pi in props)
            {
                pi.SetValue(obj, System.Convert.ChangeType(datas[pi.Name], pi.PropertyType), null);
            }

            // 按ID-数据的形式存储
            dict[System.Convert.ToInt32(id)] = obj;
        }

        return dict;
    }

    /// <summary>
    /// CSV文件-》C#类文件
    /// </summary>
    /// <param name="src_filePath"></param>
    /// <param name="dst_filepath"></param>
    public static void CsvFileToCSharpClass(string src_filePath, string dst_filepath = "")
    {
        //读取所有的数据
        string[] lines = File.ReadAllLines(src_filePath);

        //类型
        string[] typeName = lines[0].Split(',');
        StrArrTrim(typeName);
        //属性
        string[] variableName = lines[1].Split(',');
        StrArrTrim(variableName);
        //注释
        //string[] noteStr = lines[2].Split(',');
        //StrArrTrim(noteStr);

        //类的名字
        string className = Path.GetFileNameWithoutExtension(src_filePath);
        //类的结构
        string code = "using System.Collections;\nusing System.Collections.Generic;\n\n";
        code += String.Format("////////////////////////////////\n/// {0}.cs——{1}信息类\n////////////////////////////////\n", className, className);
        code += String.Format("{0}public class {1} {{ \n\n", "", className);

        for (int i = 0; i < typeName.Length; i++)
        {
            //code += String.Format("\t//{0}\n", noteStr[i]);
            code += String.Format("{0}public {1} {2} {{ get; set; }}\n\n", "\t", typeName[i], variableName[i]);
        }

        code += "}\n";

        src_filePath = src_filePath.Replace("\\", "/");
        string folder = src_filePath.Substring(0, src_filePath.LastIndexOf("/") + 1);
        string CSharpFile = "";
        if (string.IsNullOrEmpty(dst_filepath))
        {
            CSharpFile = String.Format("{0}{1}.cs", folder, className);
        }
        else
        {
            CSharpFile = dst_filepath;
        }
        Console.WriteLine(CSharpFile);

        File.WriteAllText(CSharpFile, code);
    }

    private static void StrArrTrim(string[] strs)
    {
        if (strs.Length > 0)
        {
            for (int i = 0; i < strs.Length; i++)
            {
                strs[i] = strs[i].Trim();
            }
        }
    }
}
